package net.flydy.ywxcx.wxcloudrun.config;

import lombok.extern.slf4j.Slf4j;
import net.flydy.ywxcx.wxcloudrun.vo.BaseRequest;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Type;

/**
 * @author flydy
 */

@ControllerAdvice
@Slf4j
@Component
public class GlobalControllerAdvice extends RequestBodyAdviceAdapter {

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (body instanceof BaseRequest) {
            try {
                HttpHeaders httpHeaders = inputMessage.getHeaders();
                if (httpHeaders.containsKey("yourFlag")) {
                    String token = inputMessage.getHeaders().get("yourFlag").get(0);
                    ((BaseRequest) body).setToken(token);
                }
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return body;
    }


}
